/**
 * Thinking Chain Parser
 * 
 * 解析 Claude 响应中的思维链
 * 
 * 注意：这是简化版实现，用于 MVP 验证
 * 完整版需要更复杂的 NLP 解析
 */

import type { ThinkingChain, ThinkingStep, ThinkingStepType } from '@/types/thinking';

/**
 * 解析 Claude 响应，提取思维链
 */
export function parseThinkingChain(
  messageId: string,
  content: string
): ThinkingChain | null {
  const steps: ThinkingStep[] = [];
  let stepIndex = 0;
  const startTime = Date.now();

  // 1. 检测显式思维标签
  const thinkingMatches = extractThinkingTags(content);
  if (thinkingMatches.length > 0) {
    thinkingMatches.forEach((match, index) => {
      steps.push({
        id: `${messageId}_step_${stepIndex++}`,
        type: match.type,
        title: match.title,
        content: match.content,
        timestamp: startTime + index * 100,
        duration: Math.random() * 1000 + 500, // 模拟持续时间
      });
    });
  }

  // 2. 检测工具调用
  const toolCalls = extractToolCalls(content);
  toolCalls.forEach((tool, index) => {
    steps.push({
      id: `${messageId}_step_${stepIndex++}`,
      type: 'tool_use',
      title: `调用工具: ${tool.name}`,
      content: `执行 ${tool.name} 工具`,
      timestamp: startTime + stepIndex * 100,
      duration: Math.random() * 500 + 200,
      tool,
    });
  });

  // 3. ❌ 禁用智能推断，避免将整个响应当作"思维"
  // 只有在真正有 <thinking> 标签或工具调用时才显示思维链
  // if (steps.length === 0) {
  //   const inferredSteps = inferThinkingSteps(content);
  //   steps.push(...inferredSteps.map((step, index) => ({
  //     ...step,
  //     id: `${messageId}_step_${stepIndex++}`,
  //     timestamp: startTime + index * 100,
  //   })));
  // }

  // 如果没有真正的思维链数据，返回 null
  if (steps.length === 0) {
    return null;
  }

  const endTime = Date.now();

  return {
    id: `thinking_${messageId}`,
    messageId,
    steps,
    totalDuration: steps.reduce((sum, step) => sum + (step.duration || 0), 0),
    startTime: new Date(startTime),
    endTime: new Date(endTime),
    completed: true,
  };
}

/**
 * 提取显式思维标签
 */
function extractThinkingTags(content: string): Array<{
  type: ThinkingStepType;
  title: string;
  content: string;
}> {
  const results: Array<{ type: ThinkingStepType; title: string; content: string }> = [];

  // 定义标签映射
  const tagPatterns: Array<{ regex: RegExp; type: ThinkingStepType; title: string }> = [
    { regex: /<thinking>(.*?)<\/thinking>/gs, type: 'reasoning', title: '思考过程' },
    { regex: /<reasoning>(.*?)<\/reasoning>/gs, type: 'reasoning', title: '推理分析' },
    { regex: /<analysis>(.*?)<\/analysis>/gs, type: 'analysis', title: '深入分析' },
    { regex: /<planning>(.*?)<\/planning>/gs, type: 'planning', title: '计划制定' },
    { regex: /<conclusion>(.*?)<\/conclusion>/gs, type: 'conclusion', title: '得出结论' },
    { regex: /<reflection>(.*?)<\/reflection>/gs, type: 'reflection', title: '反思评估' },
  ];

  tagPatterns.forEach(({ regex, type, title }) => {
    const matches = content.matchAll(regex);
    for (const match of matches) {
      results.push({
        type,
        title,
        content: match[1].trim(),
      });
    }
  });

  return results;
}

/**
 * 提取工具调用
 */
function extractToolCalls(content: string): Array<{
  name: string;
  input?: any;
  output?: any;
}> {
  const toolCalls: Array<{ name: string; input?: any; output?: any }> = [];

  // 简单的工具调用检测（基于常见模式）
  const toolPatterns = [
    /使用.*?(\w+).*?工具/g,
    /调用.*?(\w+).*?功能/g,
    /执行.*?(\w+).*?操作/g,
  ];

  toolPatterns.forEach(pattern => {
    const matches = content.matchAll(pattern);
    for (const match of matches) {
      toolCalls.push({
        name: match[1],
      });
    }
  });

  return toolCalls;
}

/**
 * 智能推断思维步骤（当没有显式标签时）
 */
function inferThinkingSteps(content: string): Omit<ThinkingStep, 'id' | 'timestamp'>[] {
  const steps: Omit<ThinkingStep, 'id' | 'timestamp'>[] = [];

  // 按段落分割
  const paragraphs = content
    .split(/\n\n+/)
    .filter(p => p.trim().length > 20); // 过滤太短的段落

  if (paragraphs.length === 0) {
    return [];
  }

  // 为每个段落推断类型
  paragraphs.forEach((paragraph, index) => {
    const type = inferStepType(paragraph, index, paragraphs.length);
    const title = generateStepTitle(type, index);

    steps.push({
      type,
      title,
      content: paragraph.trim(),
      duration: Math.random() * 800 + 400,
    });
  });

  return steps;
}

/**
 * 推断步骤类型
 */
function inferStepType(
  paragraph: string,
  index: number,
  total: number
): ThinkingStepType {
  const lowerPara = paragraph.toLowerCase();

  // 结论通常在最后
  if (index === total - 1 && (
    lowerPara.includes('因此') ||
    lowerPara.includes('总结') ||
    lowerPara.includes('综上') ||
    lowerPara.includes('所以')
  )) {
    return 'conclusion';
  }

  // 分析关键词
  if (
    lowerPara.includes('分析') ||
    lowerPara.includes('观察') ||
    lowerPara.includes('发现')
  ) {
    return 'analysis';
  }

  // 计划关键词
  if (
    lowerPara.includes('计划') ||
    lowerPara.includes('步骤') ||
    lowerPara.includes('首先') ||
    lowerPara.includes('然后')
  ) {
    return 'planning';
  }

  // 反思关键词
  if (
    lowerPara.includes('回顾') ||
    lowerPara.includes('检查') ||
    lowerPara.includes('验证')
  ) {
    return 'reflection';
  }

  // 默认为推理
  return 'reasoning';
}

/**
 * 生成步骤标题
 */
function generateStepTitle(type: ThinkingStepType, index: number): string {
  const titles: Record<ThinkingStepType, string> = {
    reasoning: '推理分析',
    tool_use: '工具调用',
    retrieval: '知识检索',
    analysis: '深入分析',
    planning: '计划制定',
    conclusion: '得出结论',
    reflection: '反思评估',
  };

  return `${titles[type]} ${index + 1}`;
}

/**
 * 生成思维链摘要
 */
export function generateThinkingSummary(chain: ThinkingChain): string {
  const stepTypes = chain.steps.reduce((acc, step) => {
    acc[step.type] = (acc[step.type] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  const parts: string[] = [];
  
  if (stepTypes.reasoning) parts.push(`${stepTypes.reasoning}个推理步骤`);
  if (stepTypes.analysis) parts.push(`${stepTypes.analysis}个分析过程`);
  if (stepTypes.tool_use) parts.push(`${stepTypes.tool_use}次工具调用`);
  if (stepTypes.conclusion) parts.push(`得出结论`);

  return `经过 ${parts.join('、')}，用时 ${(chain.totalDuration / 1000).toFixed(1)}秒`;
}

/**
 * 验证思维链
 */
export function validateThinkingChain(chain: ThinkingChain): {
  valid: boolean;
  errors: string[];
} {
  const errors: string[] = [];

  if (!chain.steps || chain.steps.length === 0) {
    errors.push('思维链没有步骤');
  }

  chain.steps.forEach((step, index) => {
    if (!step.content || step.content.trim().length === 0) {
      errors.push(`步骤 ${index + 1} 内容为空`);
    }
    if (!step.type) {
      errors.push(`步骤 ${index + 1} 缺少类型`);
    }
  });

  return {
    valid: errors.length === 0,
    errors,
  };
}

